# -*- coding: utf-8 -*-
import pygame
import sys
def gcShow(gc, font, surface):
    gcButtonNames = ("Tri","Circlr","Cross","Square", "LB", "RB", "LT", "RT", "Select","Start", "LPush", "RPush")
    tName = font.render("Name : "+gc.get_name(),True,(255,255,255))
    tAxis = font.render("Axes : "+str(gc.get_numaxes()),True,(255,255,255))
    tButton = font.render("Buttons : "+str(gc.get_numbuttons()),True,(255,255,255))
    tPressed = ""
    for i in range(gc.get_numbuttons()):
        if (gc.get_button(i)):
            tPressed += gcButtonNames[i]
            tPressed += " "
    tPress = font.render(tPressed,True,(128,128,128))
    hori = int(gamer1.get_axis(0)*10)
    vert = int(gamer1.get_axis(1)*10)
    msg = "(" + str(hori) + "," + str(vert) + ")"
    text1 = font.render(msg, True, (255,255,0))
    if hori < 0 and vert == 0:
        text2 = font.render("Left",True,(0,255,0))
    elif hori == 0 and vert > 0:
        text2 = font.render("Down",True,(0,255,0))
    elif hori > 0 and vert == 0:
        text2 = font.render("Right",True,(0,255,0))
    elif hori == 0 and vert < 0:
        text2 = font.render("Up",True,(0,255,0))
    elif hori < 0 and vert < 0:
        text2 = font.render("Left+Up",True,(0,128,255))
    elif hori < 0 and vert > 0:
        text2 = font.render("Left+Down",True,(0,128,255))
    elif hori > 0 and vert < 0:
        text2 = font.render("Right+Up",True,(0,128,255))
    elif hori > 0 and vert > 0:
        text2 = font.render("Right+Down",True,(0,128,255))
    else:
        text2 = font.render("Center", True, (255,0,255))
    tw1, th1 = text1.get_size()
    tw2, th2 = text2.get_size()
    sw, sh = surface.get_size()
    tx1 = (sw-tw1)/2
    ty1 = (sh-th1)/2
    tx2 = (sw-tw2)/2
    ty2 = (sh-th2)/2
    surface.blit(text1,(tx1,ty1))
    surface.blit(text2,(tx2,ty2-th2))
    surface.blit(tName,(0,0))
    surface.blit(tAxis,(0,th2))
    surface.blit(tButton,(0,th2*2))
    surface.blit(tPress,(0,th2*3))

pygame.init()
gcCnt = pygame.joystick.get_count()
if gcCnt == 0:
    print("Error.....")
    sys.exit()
fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Ex17.9")
pygame.display.set_caption("Game Controller")
gamer1 = pygame.joystick.Joystick(0)
gamer1.init()
background = pygame.Color( 0, 0, 0)
font = pygame.font.SysFont("Tahoma", 40)

running = True
while running:
    fpsClock.tick(30)
    screen.fill(background)
    gcShow( gamer1, font, screen )
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.JOYBUTTONDOWN:
            gcShow(gamer1, font, screen)
        if event.type == pygame.JOYBUTTONUP:
            gcShow(gamer1, font, screen)
    pygame.display.flip()
pygame.quit()